package com.example.etwzgzxt.view.fragment;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.overlayutil.DrivingRouteOverlay;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.baidu.mapapi.search.route.BikingRouteResult;
import com.baidu.mapapi.search.route.DrivingRoutePlanOption;
import com.baidu.mapapi.search.route.DrivingRouteResult;
import com.baidu.mapapi.search.route.OnGetRoutePlanResultListener;
import com.baidu.mapapi.search.route.PlanNode;
import com.baidu.mapapi.search.route.RoutePlanSearch;
import com.baidu.mapapi.search.route.TransitRouteResult;
import com.baidu.mapapi.search.route.WalkingRouteResult;
import com.baidu.mapapi.utils.route.BaiduMapRoutePlan;
import com.example.etwzgzxt.R;
import com.example.etwzgzxt.tool.HttpHelper;
import com.example.etwzgzxt.tool.InfoApplication;
import com.example.etwzgzxt.tool.tool;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import cz.msebera.android.httpclient.NameValuePair;
import cz.msebera.android.httpclient.message.BasicNameValuePair;
/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 *
 * to handle interaction events.
 * Use the {@link MainFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class MainFragment extends Fragment implements OnGetGeoCoderResultListener,View.OnClickListener {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private MapView mMapView = null;
    private BaiduMap mBaiduMap;
    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2,makertitle="";
    private   PopupWindow  popupWindow;
    public LocationClient mLocationClient = null;
    public BDLocationListener myListener ;
    private BMapManager mBMapManager=null;
    public static final int GET_LIST = 1;
   // public static final int DELETE = 2;
    public MainFragment() {
        // Required empty public constructor
    }
private Button btnnavi,btncancel;
    private EditText editholder;
    public static MainFragment newInstance(String param1, String param2) {
        MainFragment fragment = new MainFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

   @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
        myListener = new MyLocationListener();
        mLocationClient = new LocationClient(getActivity());     //声明LocationClient类
        mLocationClient.registerLocationListener( myListener );    //注册监听函数
        initLocation();
        mLocationClient.start();
       Toast.makeText(getActivity(),"开始定位",Toast.LENGTH_SHORT).show();

    }
    RoutePlanSearch  routePlanSearch=null;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View v=inflater.inflate(R.layout.fragment_main, container, false);
        btnnavi= (Button)v.findViewById(R.id.navi);
        btncancel= (Button)v.findViewById(R.id.cancelnavi);
        editholder= (EditText)v.findViewById(R.id.holdername);
        mMapView = (MapView)v. findViewById(R.id.bmapView);
        mBaiduMap = mMapView.getMap();
        mSearch =GeoCoder.newInstance();
        mSearch.setOnGetGeoCodeResultListener(this);
        btnnavi.setOnClickListener(this);
        btncancel.setOnClickListener(this);

        mBaiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                 Bundle b=marker.getExtraInfo();
          if(b!=null||!b.isEmpty())
              makertitle=b.getString("title");
                mSearch.reverseGeoCode(new ReverseGeoCodeOption().location(marker.getPosition()));

                return false;
            }
        });
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.marker);

        Matrix matrix = new Matrix();
        matrix.postScale(0.2f,0.2f); //长和宽放大缩小的比例
        Bitmap resizeBmp = Bitmap.createBitmap(bitmap,0,0,bitmap.getWidth(),bitmap.getHeight(),matrix,true);
        bitmap1 = BitmapDescriptorFactory.fromBitmap(resizeBmp);
        routePlanSearch= RoutePlanSearch.newInstance();
        return v;
    }

   @Override
    public void onDestroyView() {
        super.onDestroyView();
        mMapView.onDestroy();
    }


    @Override
    public void onResume() {
        super.onResume();
        mMapView.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        mMapView.onPause();
    }

    BitmapDescriptor bitmap1 = null;
 public void addMaker(LatLng point,Bundle b,int i){
     if(marker==null)
         return;
     OverlayOptions option = new MarkerOptions() .position(point) .icon(bitmap1);

     //结束调启功能时调用finish方法以释放相关资源
     BaiduMapRoutePlan.finish(getActivity());


         marker[i] = (Marker) (mBaiduMap.addOverlay(option));
         marker[i].setExtraInfo(b);


 }

    Marker[] marker=new Marker[10];

    public void removeMaker(){
        mBaiduMap.clear();


    }

    public void setcenter(  LatLng point){

        MapStatus mMapStatus = new MapStatus.Builder()
                .target(point)
                .zoom(10)
                .build();
        //定义MapStatusUpdate对象，以便描述地图状态将要发生的变化

        MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mMapStatus);
        //改变地图状态
        mBaiduMap.setMapStatus(mMapStatusUpdate);


    }

    @Override
    public void onClick(View v) {
        switch (v.getId())
        {
            case R.id.navi:
                String holder=editholder.getText().toString();
                BDLocation point=((InfoApplication)getActivity().getApplicationContext()).getMyPoi();

                if(holder!=null&&holder!=""&&point!=null)
                {
                    if(devicelist!=null)
                    {
                        JSONObject message=null,device=null;
                        Double lat=null,lon=null;

                        for (int i = 0; i < devicelist.length(); i++) {

                            try {
                                if(devicelist.getJSONObject(i).getString("holder").equals(holder)) {
                                    device = devicelist.getJSONObject(i);
                                    message = device.getJSONObject("message");
                                    lat=message.getDouble("latitude");
                                    lon=message.getDouble("longtitude");
                                }
                            }catch (Exception e)
                            {
                                e.printStackTrace();
                            }

                        }
                        if(message!=null&&device!=null)
                        {
                            LatLng pt_start = new LatLng(point.getLatitude(),point.getLongitude());
                            LatLng pt_end = new LatLng(lat, lon);
                            DrivingRoutePlanOption drivingOption = new DrivingRoutePlanOption();
                            drivingOption.policy(DrivingRoutePlanOption.DrivingPolicy.ECAR_AVOID_JAM);// 设置驾车路线策略
                            drivingOption.from(PlanNode.withLocation(pt_start));// 设置起点
                            drivingOption.to(PlanNode.withLocation(pt_end));// 设置终点
                            routePlanSearch.setOnGetRoutePlanResultListener(new OnGetRoutePlanResultListener() {
                                @Override
                                public void onGetWalkingRouteResult(WalkingRouteResult walkingRouteResult) {

                                }

                                @Override
                                public void onGetTransitRouteResult(TransitRouteResult transitRouteResult) {

                                }



                                @Override
                                public void onGetBikingRouteResult(BikingRouteResult bikingRouteResult) {

                                }
                                @Override
                                public void onGetDrivingRouteResult(
                                        DrivingRouteResult drivingRouteResult) {
                                    mBaiduMap.clear();
                                    if (drivingRouteResult == null
                                            || drivingRouteResult.error != SearchResult.ERRORNO.NO_ERROR) {
                                        Toast.makeText(getActivity(), "抱歉，未找到结果",
                                                Toast.LENGTH_SHORT).show();
                                    }
                                    if (drivingRouteResult.error == SearchResult.ERRORNO.AMBIGUOUS_ROURE_ADDR) {
                                        // 起终点或途经点地址有岐义，通过以下接口获取建议查询信息
                                        // drivingRouteResult.getSuggestAddrInfo()
                                        return;
                                    }
                                    if (drivingRouteResult.error == SearchResult.ERRORNO.NO_ERROR) {
                                        DrivingRouteOverlay drivingRouteOverlay = new DrivingRouteOverlay(
                                                mBaiduMap);
                                        drivingRouteOverlay.setData(drivingRouteResult.getRouteLines()
                                                .get(0));// 设置一条驾车路线方案
                                        mBaiduMap.setOnMarkerClickListener(drivingRouteOverlay);
                                        drivingRouteOverlay.addToMap();
                                        drivingRouteOverlay.zoomToSpan();
                                        int  totalLine = drivingRouteResult.getRouteLines().size();
                                        Toast.makeText(getActivity(),
                                                "共查询出" + totalLine + "条符合条件的线路",  Toast.LENGTH_SHORT).show();


                                    }
                                }

                            });
                            routePlanSearch.drivingSearch(drivingOption);// 发起驾车路线规划
                            if(timer!=null)
                                timer.cancel();
                        }
                        else{

                        }

                    }

                }


            break;
            case R.id.cancelnavi:
                timer=new Timer();
                timer.schedule(new Work(),10000);
                editholder.setText("");
                mBaiduMap.clear();

            break;
        }
    }


    public class MyLocationListener implements BDLocationListener {
        StringBuffer sb = null;
        @Override
        public void  onReceiveLocation(BDLocation location) {


     if (location.getLocType() == BDLocation.TypeGpsLocation||location.getLocType() == BDLocation.TypeNetWorkLocation) {// GPS定位结果
         //Toast.makeText(getActivity(),"定位结束",Toast.LENGTH_SHORT).show();
                 LatLng point = new LatLng(location.getLatitude(),location.getLongitude());
         ((InfoApplication)getActivity().getApplicationContext()).setMyPoi(location);

         //addMaker(point,new Bundle(),0);
//setcenter(point);

            } else{
         sb = new StringBuffer(256);
               if (location.getLocType() == BDLocation.TypeServerError) {
                    sb.append("\ndescribe : ");
                    sb.append("服务端网络定位失败，可以反馈IMEI号和大体定位时间到loc-bugs@baidu.com，会有人追查原因");
                } else if (location.getLocType() == BDLocation.TypeNetWorkException) {
                    sb.append("\ndescribe : ");
                    sb.append("网络不同导致定位失败，请检查网络是否通畅");
                } else if (location.getLocType() == BDLocation.TypeCriteriaException) {
                    sb.append("\ndescribe : ");
                    sb.append("无法获取有效定位依据导致定位失败，一般是由于手机的原因，处于飞行模式下一般会造成这种结果，可以试着重启手机");
                }
               Toast.makeText(getActivity(),sb.toString(),Toast.LENGTH_SHORT).show();
            }

        ;
        }
    }
    private void initLocation(){
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy
        );
        // option.setCoorType("bd09ll");//可选，默认gcj02，设置返回的定位结果坐标系
        int span=10000;
        option.setScanSpan(span);
        option.setIsNeedAddress(true);
        option.setOpenGps(true);
        option.setCoorType("bd09ll");
       // option.setLocationNotify(true);
        option.setIsNeedLocationDescribe(true);//可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
        option.setIsNeedLocationPoiList(false);//可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
        option.setIgnoreKillProcess(false);//可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死
        option.SetIgnoreCacheException(true);//可选，默认false，设置是否收集CRASH信息，默认收集
        option.setEnableSimulateGps(true);//可选，默认false，设置是否需要过滤gps仿真结果，默认需要
        mLocationClient.setLocOption(option);
    }
    public class BackgroundTask extends AsyncTask<Void, Void, String> {

        int type;

        public BackgroundTask(int type) {
            this.type = type;
        }

        @Override
        protected String doInBackground(Void... params) {
         //   if (type == GET_LIST) {
                return getList();
           // }
           // else {
              //  return delete();
           // }
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            parseResult(result, type);
        }
    }
    class Work extends TimerTask {

        @Override
        public void run() {
            if ( tool.isNetworkAvailable(getActivity().getApplicationContext()))
            {


                BDLocation point = ((InfoApplication) getActivity().getApplicationContext()).getMyPoi();
                if (point != null) {
                    mBaiduMap.clear();
                    Bundle b = new Bundle();
                    b.putString("title", "您的位置:");
                    b.putString("address", point.getAddrStr());
                    LatLng l = new LatLng(point.getLatitude(), point.getLongitude());

                    addMaker(l, b,0);
                    setcenter(l);


                }
                new BackgroundTask(GET_LIST).execute();
                // parseResult(getList(),GET_LIST);
            }
        }
    }
    Timer timer=null;
    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);


        if(!hidden) {
            timer = new Timer();
            timer.schedule(new Work(),0, 10000);

        }
        else
        if(timer!=null)
            timer.cancel();

    }
    public String getList() {
        String baseURL =   ((InfoApplication)getActivity(). getApplicationContext()).getBasehost()+"/device/getlastmessage.do";
        List<NameValuePair> pair = new ArrayList<>();

        pair.add( new BasicNameValuePair("access_token", ((InfoApplication) getActivity().getApplication()).getAccess_token()));


        for (NameValuePair pairs: pair) {
            System.out.println(pairs.getName()+" "+pairs.getValue());
        }
        return new HttpHelper().post(baseURL, pair);
    }

//    public String delete() {
//        String baseURL =  ((InfoApplication)getActivity(). getApplicationContext()).getBasehost()+"/device/deletebytime.do";
//        List<NameValuePair> pair = new ArrayList<>();
//        pair.add( new BasicNameValuePair("access_token", ((InfoApplication)  getActivity().getApplication()).getAccess_token()));
//
//        for (NameValuePair pairs: pair) {
//            System.out.println(pairs.getName()+" "+pairs.getValue());
//        }
//        return new HttpHelper().post(baseURL, pair);
//    }
public JSONArray devicelist;
    public void parseResult(String result, int type) {
        try {
            JSONObject jsonObject = new JSONObject(result);
            switch (jsonObject.getInt("code")) {
                case 200:
                    if (type == GET_LIST) {
                        try {
                           // messagelist = new JSONArray(jsonObject.getString("result"));
                            devicelist = new JSONArray(jsonObject.getString("result"));

                            if(devicelist!=null)
                            {

                                int length = devicelist.length();

                                JSONObject message,device;

                                for (int i = 0; i < length; i++) {

                               if(!devicelist.getString(0).equals("null"))
                               {
                                   device = devicelist.getJSONObject(i);
                                   String tmp=device.getString("message");
                                   System.out.println("设备及其位置信息"+device.get("deviceid")+"        "+tmp);
                                    message=new JSONObject(tmp);
                              if(message!=null||device!=null) {

                                  LatLng point = new LatLng(message.getDouble("latitude"), message.getDouble("longtitude"));
                                  System.out.println("设备"+device.get("deviceid")+" latitude  "+"   "+message.getDouble("latitude")+"  longtitude  "+message.getDouble("longtitude"));
                                  Bundle b=new Bundle();
                                  b.putString("title","您孩子"+device.getString("holder")+"的位置:");
                                  b.putString("address","");
                                  addMaker(point,b,i);

                              }
                              }
                                }

                            }
                            else
                                Toast.makeText(getActivity(),"没有信息",Toast.LENGTH_SHORT).show();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else {
                        Toast.makeText(getActivity(),"删除成功",Toast.LENGTH_SHORT).show();
                        new BackgroundTask(GET_LIST).execute();
                    }
                    break;
                case 403:
                    break;
                case 406:
                    break;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if (result == null) {
            Toast.makeText(getActivity(), "请检查网络设置", Toast.LENGTH_SHORT).show();
            return;
        }

    }
    private GeoCoder mSearch = null; // 搜索模块
    @Override
    public void onGetGeoCodeResult(GeoCodeResult result) {

    }

    @Override
    public void onGetReverseGeoCodeResult(final ReverseGeoCodeResult result) {
        if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
            //  Bundle b=marker.getExtraInfo();

            return;
        }
        else{
            TextView textView=new TextView(getActivity());
            textView.setText(result.getAddress());
            AlertDialog alertDialog=new AlertDialog.Builder(getActivity()).setTitle(makertitle).setView(textView).setNegativeButton("确定",null).show();
            System.out.println((result == null) +"   "+(result.error != SearchResult.ERRORNO.NO_ERROR)+"  "+result.getLocation()+"  "+result.getAddress()+"   "+result.getAddressDetail());
         //   addMaker(result.getLocation(),b);
            makertitle="";
        }
    }


}
